const app = getApp()
const utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    mobile : '',
    from : '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.from) {
      var type = options.from;
      this.setData({
        "from": type
      });
      if (type == 'change') {
        wx.setNavigationBarTitle({
          title: '更换手机号码'
        })
      }
    }

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  bindMobileInput: function(e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  //确认提交
  bindSubmit : function(e) {
    let mobile = this.data.mobile;
    let that = this;
    // || !utils.isPhone(mobile)
    if (undefined === mobile || mobile == '') {
      wx.showModal({
        title: '提示',
        content: '请输入正确的手机号码',
        showCancel: false,
        success(res) { }
      });
      return false;
    }
    utils.wxlogin().then(function (wxloginRes) {
      let code = wxloginRes.code,
        params = {
          code : code,
          phone : mobile
        };
      utils.promiseRequest('/wx/user/updatePhone', 'GET', params).then(function(res){
        if (res.code == 200) {
          wx.showModal({
            title: that.data.from == 'index' ? '绑定成功' : '更改成功',
            content: '',
            showCancel : false,
            success (res) {
              if (res.confirm) {
                wx.removeStorageSync('token');
                wx.removeStorageSync('userInfo');
                wx.reLaunch({
                  url: '/pages/index/index',
                });
              }
            }
          });       
        } else {
          wx.showModal({
            title: '提示',
            content: res.message,
            showCancel: false,
            success(res) {}
          });
        }
      }).catch(e => {
        console.log(e);
      });
    }).catch(function(e){
      console.log(e);
    });
  }
})